package com.runfast.paotui.task.scheduler;

import com.runfast.common.web.entity.Result;
import com.runfast.paotui.dao.model.Order;
import com.runfast.paotui.dao.model.OrderExample;
import com.runfast.paotui.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * @author: lijin
 * @date: 2018年04月16日
 */
@Component
@Slf4j
public class OrderScheduler {

    @Autowired
    private OrderService orderService;
    /**
     * 定时处理订单
     */
    @Scheduled(fixedDelay = 60 * 1000)
    public void handle() {
        log.info("开始跑腿订单定时任务");
        // 超时取消新创建或者已付款的订单
        asyncCancelOrder();



        //超时完成订单（骑手已接单）
        asyncCompleteOrder();

        //超时确认取消申请
        asyncConfirmCancel();

    }

    @Async
    void asyncCancelOrder( ){

        OrderExample orderPaidExample = new OrderExample();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, -10);
        orderPaidExample.or().andStatusEqualTo(Order.Status.CREATED.ordinal()).andCreateTimeLessThan(instance.getTime());
        orderPaidExample.or().andStatusEqualTo(Order.Status.PAID.ordinal()).andCreateTimeLessThan(instance.getTime());

        List<Map<String, Integer>> maps = orderService.selectIdUserIdByExample(orderPaidExample);
        for (Map<String, Integer> map : maps) {
            Integer id = map.get("id");
            Integer userId = map.get("userId");

            try{
                orderService.cancel(userId, id);
            }catch (Exception e){
                log.error("用户id：{} , 订单id：{}",userId,id, e);
            }

        }

    }


    @Async
    public void asyncCompleteOrder() {

        OrderExample orderExample = new OrderExample();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, -5);
        orderExample.createCriteria().andStatusEqualTo(Order.Status.TAKEN.ordinal()).andCreateTimeLessThan(instance.getTime());

        List<Map<String, Integer>> maps = orderService.selectIdUserIdByExample(orderExample);
        for (Map<String, Integer> map : maps) {
            Integer id = map.get("id");
            Integer userId = map.get("userId");

            try{
                orderService.complete(userId, id);
            }catch (Exception e){
                log.error("用户id：{} , 订单id：{}",userId,id, e);

            }

        }

    }

    @Async
    void asyncConfirmCancel() {
        log.debug("系统确认超过2小时未处理的取消申请订单");
        /**
         * 超过2小时，自动确认取消申请
         */
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, -2);


        List<Map<String, Integer>> maps = orderService.findConfirmCancelOrder(instance.getTime());
        for (Map<String, Integer> map : maps) {
            Integer id = map.get("id");
            Integer userId = map.get("userId");


            try {
                orderService.confirmCancel(userId, id);
            }catch (Exception e){
                log.error("用户id：{} , 订单id：{}",userId,id, e);
            }
        }

    }
}
